package com.sl.au.service.impl;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.repository.Query;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.sl.au.entity.ArchiveInfo;
import com.sl.au.entity.EventRegister;
import com.sl.au.entity.EventReport;
import com.sl.au.entity.EventTask;
import com.sl.au.entity.Option;
import com.sl.au.repository.ArchiveInfoRepository;
import com.sl.au.repository.EventRegisterRepository;
import com.sl.au.repository.EventReportRepository;
import com.sl.au.repository.EventTaskRepository;
import com.sl.au.repository.OptionRepository;
import com.sl.au.service.ArchiveInfoService;

@Service
@Transactional
public class ArchiveInfosServiceImpl extends BaseServiceImpl implements ArchiveInfoService {

	@Autowired
	private ArchiveInfoRepository archiveInfoRepository;
	@Autowired
	private OptionRepository optionRepository;
	@Autowired
	private EventRegisterRepository eventRegisterRepository;
	@Autowired
	private EventTaskRepository eventTaskRepository;
	@Autowired
	private EventReportRepository eventReportRepository;
	@Resource
	private JdbcTemplate jdbcTemplate;

	@Override
	public List<ArchiveInfo> getArchivePageByKey(int start, int length, String key, String orderName, String dir) {
		Pageable pageable = new PageRequest(start / length, length, Sort.Direction.DESC, "createTime");
		return archiveInfoRepository.getArchivePageByKey(key, pageable).getContent();
	}

	@Override
	public List<ArchiveInfo> getArchivePage(int start, int length, String key, String orderName, String dir) {
		Pageable pageable = new PageRequest(start / length, length, Sort.Direction.DESC, "createTime");
		return archiveInfoRepository.getArchivePage(pageable).getContent();
	}

	@Override
	public Integer getArchiveCount(String key) {
		Pageable pageable = new PageRequest(0, Integer.MAX_VALUE, Sort.Direction.DESC, "createTime");
		if (!StringUtils.hasText(key)) {
			return archiveInfoRepository.getArchivePage(pageable).getContent().size();
		}
		return archiveInfoRepository.getArchivePageByKey(key, pageable).getContent().size();
	}

	@Override
	public void deleteById(String id) {
		archiveInfoRepository.delete(archiveInfoRepository.findOne(id));

	}

	@Override
	public ArchiveInfoRepository getRepository() {

		return archiveInfoRepository;
	}

	@Override
	public void saveMany(EventRegister register, ArchiveInfo archiveInfo) {
		Option option = optionRepository.findByGroupAndTitle("内部事件流转状态", "已完结").get(0);
		register.setRegisterEventState(option);
		eventRegisterRepository.save(register);
		archiveInfo.setRegister(register);
		archiveInfoRepository.save(archiveInfo);

	}

	@Override
	public void saveMany(EventRegister register, ArchiveInfo archiveInfo, EventTask registerTask, EventTask reportTask,
			EventReport eventReport) {
		// 保存自身内部事件
		Option option = optionRepository.findByGroupAndTitle("内部事件流转状态", "已完结").get(0);
		register.setRegisterEventState(option);
		eventRegisterRepository.save(register);

		// 保存自身内部的归档信息
		archiveInfo.setRegister(register);
		archiveInfoRepository.save(archiveInfo);

		// 保存自身内部事件的日志信息
		registerTask.setCreateTime(new Date());
		registerTask.setEventId(register.getId());
		registerTask.setEventTaskMemo(register.getRegisterEventMemo());
		registerTask.setEventTaskState(register.getRegisterEventState());
		registerTask.setEventTaskTime(new Date());
		registerTask.setEventTaskUser(archiveInfo.getArchiver());
		registerTask.setEventTaskOperate("归档内部事件");
		registerTask.setPhotoUrl(archiveInfo.getPhotourl());
		eventTaskRepository.save(registerTask);

		// 保存事件源的信息
		Option opt = optionRepository.findByGroupAndTitle("事件上报状态", "已完结").get(0);
		eventReport.setReportEventVariable(opt);
		eventReportRepository.save(eventReport);

		// 保存事件源的日志信息
		reportTask.setCreateTime(new Date());
		reportTask.setEventId(eventReport.getId());
		reportTask.setEventTaskMemo(eventReport.getReportMemo());
		reportTask.setEventTaskState(eventReport.getReportEventVariable());
		reportTask.setEventTaskTime(new Date());
		reportTask.setEventTaskUser(archiveInfo.getArchiver());
		reportTask.setEventTaskOperate("完结事件源[内部事件全部完结,待归档]");
		eventTaskRepository.save(reportTask);
	}

	@Override
	public void saveMany(EventRegister register, EventTask registerTask, ArchiveInfo archiveInfo) {
		// 保存自身内部事件
		Option option = optionRepository.findByGroupAndTitle("内部事件流转状态", "已完结").get(0);
		register.setRegisterEventState(option);
		eventRegisterRepository.save(register);

		// 保存自身内部的归档信息
		archiveInfo.setRegister(register);
		archiveInfoRepository.save(archiveInfo);
		// 保存自身内部事件的日志信息
		registerTask.setEventId(register.getId());
		registerTask.setCreateTime(new Date());
		registerTask.setEventTaskMemo(register.getRegisterEventMemo());
		registerTask.setEventTaskState(register.getRegisterEventState());
		registerTask.setEventTaskTime(new Date());
		registerTask.setEventTaskUser(archiveInfo.getArchiver());
		registerTask.setEventTaskOperate("归档内部事件");
		eventTaskRepository.save(registerTask);

	}

	@Override
	public List<ArchiveInfo> findArchiveByRegisterId(String eventId) {

		return archiveInfoRepository.findArchiveByRegisterId(eventId);
	}

	
	@Override
	public List<Map<String, Object>> getArchivePageByKeyAndRole(int start, int length, String roleId, String key, String orderName, String dir){
		
		//  @Query("select a from ArchiveInfo a where a.memo like %?1% or a.content like %?1% or a.register.registerEventName like %?1%")
		
		String SQL1 = "select  a.*, "
				+ " e.registerEventName, "
				+ " e.registerEventType, "
				+ " u.name as 'dealUserName', "
				+ " et.eventName as 'eventTypeName' "
				+ " from sl_wcsi_archive a "
				+ " left join sl_wcsi_EventRegister e on e.id = a.registerId "
				+ " left join sl_dcms_eventType et on e.registerEventType = et.id "
				+ " left join sl_au_user u on u.id = a.dealUserId "
				+ " where 1 = 1 ";
		
		if(StringUtils.hasText(key)){
			SQL1+=" and (a.memo like '%"+key+"%' or a.content like '%"+key+"%' or e.registerEventName like '%"+key+"%') ";	
		}
		
		String SQL = " select sq.* from (select e2r.* from sl_wcsi_e2r e2r where e2r.roleId = '"+ roleId +"' ) er left join ( " + SQL1 + " ) sq on er.eventTypeId = sq.registerEventType where sq.id is not null ";
		
		SQL += " order by sq." + orderName + " " + ( StringUtils.hasText(dir) ? dir : "" );
		SQL += " limit "+ (int)(Math.floor(start / length) * length) + " , " +  (int)((Math.floor(start / length) + 1) * length);
		
		List<Map<String, Object>> resultList = this.jdbcTemplate.queryForList(SQL);
		
		return resultList;
	}
	
	@Override
	public int getArchiveCountByRole(String roleId, String key) {
		String SQL1 = "select  a.*, "
				+ " e.registerEventName, "
				+ " e.registerEventType, "
				+ " u.name as 'dealUserName' "
				+ " from sl_wcsi_archive a "
				+ " left join sl_wcsi_EventRegister e on e.id = a.registerId "
				+ " left join sl_au_user u on u.id = a.dealUserId "
				+ " where 1 = 1 ";
		
		if(StringUtils.hasText(key)){
			SQL1+=" and (a.memo like '%"+key+"%' or a.content like '%"+key+"%' or e.registerEventName like '%"+key+"%') ";	
		}
		
		String SQL = " select count(1) from (select e2r.* from sl_wcsi_e2r e2r where e2r.roleId = '"+ roleId +"' ) er left join ( " + SQL1 + " ) sq on er.eventTypeId = sq.registerEventType where sq.id is not null ";
		
		int count = 0;
		count = this.jdbcTemplate.queryForObject(SQL, Integer.class);
		
		return count;
	}
}
